import React, { useEffect, useState } from 'react'
import AppDialog from '../../components/AppDialog'
import { Form, Input, Select, Button, Space } from 'antd';
import { setRoles } from '../../api/user'

const { Option } = Select;

const SetUserRole = ({ visible, userInfo, onHide, rolesList }) => {
  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (visible && userInfo.id) {
      const initialValues = {
        username: userInfo.username,
        role_name: userInfo.role_name,
        roleId: ""
      }
      form.setFieldsValue(initialValues)
    }
  }, [userInfo])

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true);
    values.id = userInfo.id
    await setRoles(values).finally(() => {
      setLoading(false)
    });
    Message("success", "更新角色成功");
   
    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    onHide(type)
  };

  return (visible ?
    <AppDialog
      title="分配角色"
      visible={visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item label="用户名" name="username">
          <Input disabled />
        </Form.Item>
        <Form.Item label="当前的角色" name="role_name">
          <Input disabled />
        </Form.Item>
        <Form.Item label="分配新角色" name="roleId">
        <Select allowClear placeholder="请选择管理员身份">
          {
            rolesList.map((item) => 
              <Option key={item.id} value={item.id}>{item.roleName}</Option> 
            )
          }
        </Select>
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              确定
            </Button>
            <Button onClick={() => handleDialogClosed()}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default SetUserRole